# -*- coding:utf-8 -*-

import pytest
from core import DataProcess
from core import ReadFileClass
from core import ReportStyle
from core import HttpRequest
import json

# 读取配置文件和用例文件
rfc = ReadFileClass("config.yaml")
case_file = ReadFileClass('%s')
http_client = HttpRequest()
data_process = DataProcess(rfc)


# 读取用例，返回用例列表作为pytest的参数
@pytest.fixture(params=case_file.get_case_by_yaml("$.test_case").current)
def case(request):
    """用例数据，测试方法参数入参该方法名 cases即可，实现同样的参数化
    目前来看相较于@pytest.mark.parametrize 更简洁。
    """
    return request.param


def test_start(case, get_token):
    """
    测试启动方法， 当需要使用 数据清洗和 数据库操作命令时将 get_db 换成 clear_db
    如只需要使用 数据库操作 则添加get_db 参数， 如一个都不需要则不添加
    :param case: 用例
    :return:
    """
    # 前置处理
    test_desc = case['test_desc']
    skip = case['skip']
    header = case['header']
    method_url = case['method_url']
    method_type = case['method_type']
    file = case['file']
    send_content = case['send_content']
    extra = case['extra']
    sql = case['sql']
    assertion = case['assertion']

    ReportStyle.title(test_desc)
    data_process.handle_case(method_url, header, skip, send_content, file)


    '''
    用于必须传content-length的接口，但是提交后依然报400 bad request，需和开发联调确定问题
    body_str = json.dumps(data_process.body)
    cl = str(len(body_str.encode()))
    data_process.headers.update({"Content-Length": cl})
    
    如果ngnix开通chunked，则可以设置下面这个header跳过content-length的检测
    data_process.headers.update({"transfer-encoding": "chunked"})
    
    用于必须传cookie的接口
    cookies = "SESSION=YmVhMDQzNTQtN2QzNC00YjY4LTgyM2ItYjU4MGNlYTE0YmVk"
    data_process.headers.update({"cookie": cookies})
    '''

    # 获取可用token，注意config文件里的server和test_basic_token设置
    authorization = get_token
    data_process.headers.update({"Authorization": authorization})

    # 发送请求
    http_client.send_request(
        method_type,
        data_process.path,
        data_process.headers,
        data_process.files,
        send_content=send_content
    )
    # 后置处理
    try:
        respjson = http_client.response.json()
        req = http_client.response.request.body
        req_header = http_client.response.request.headers
        if req:
            req_str = req.decode(encoding="utf-8")
        else:
            req_str = "{}"
        req_dict = json.loads(req_str)
        header_dict=dict(req_header)
        DataProcess.handle_extra(extra, respjson,header_dict,req_dict)
    except Exception as e:
        raise AssertionError("返回不是json")
    # DataProcess.handle_extra(extra, http_client.response.json(),data_process.headers)
    data_process.sql = sql

    # 断言
    DataProcess.assert_result(http_client.response.json(), assertion, rfc)
